package com.ngc.mall.common.configure.wxPay;

import com.ngc.mall.common.configure.LocalUser;
import com.ngc.mall.service.IOrderService;
import com.wechat.pay.java.service.payments.jsapi.JsapiServiceExtension;
import com.wechat.pay.java.service.payments.jsapi.model.Amount;
import com.wechat.pay.java.service.payments.jsapi.model.Payer;
import com.wechat.pay.java.service.payments.jsapi.model.PrepayRequest;
import com.wechat.pay.java.service.payments.jsapi.model.PrepayWithRequestPaymentResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class WxPaymentService {
    @Value("${wechat.order.pay-callback-host}")
    private String payCallbackHost;

    @Value("${wechat.order.pay-callback-path}")
    private String payCallbackPath;

    @Value("${wechat.pay.mchid}")
    private String merchantId;

    @Value("${wechat.user.appid}")
    private String appid;


    @Autowired
    private IOrderService iOrderService;


    public Map<String,String> preOrder(Long orderId) {
        String openid= LocalUser.getUser().getOpenid();
        PrepayRequest request = new PrepayRequest();
        Amount amount = new Amount();
        amount.setTotal(1);
        request.setAmount(amount);
        request.setAppid(appid);
        request.setMchid(merchantId);
        request.setDescription("订单号_"+orderId);
        request.setNotifyUrl(payCallbackHost+payCallbackPath);
        request.setOutTradeNo(String.valueOf(orderId));
        Payer payer = new Payer();
        payer.setOpenid(openid);
        request.setPayer(payer);

        JsapiServiceExtension jsapiServiceExtension= new JsapiServiceExtension
                .Builder()
                .config(WxCertificateConfig.getInstance().getConfig())
                .build();

        PrepayWithRequestPaymentResponse response=jsapiServiceExtension.prepayWithRequestPayment(request);
        Map<String, String> miniPayParams = new HashMap<>();

        miniPayParams.put("timeStamp",response.getTimeStamp());
        miniPayParams.put("package",response.getPackageVal());
        miniPayParams.put("nonceStr",response.getNonceStr());
        miniPayParams.put("signType",response.getSignType());
        miniPayParams.put("paySign", response.getPaySign());
        return miniPayParams;
    }



    /**
     * 统一下单
     */
    private void unifiedOrder(){

    }


}
